package com.tjvib.view.activity;

import static com.tjvib.Constants.SENSOR_TYPE_LOCAL;

import android.Manifest;
import android.app.AlertDialog;
import android.os.Bundle;
import android.widget.CompoundButton;

import androidx.annotation.NonNull;

import com.jjoe64.graphview.series.DataPoint;
import com.tapadoo.alerter.Alerter;
import com.tjvib.R;
import com.tjvib.presenter.LocalSensorPresenter;
import com.tjvib.sensor.LocalSensorData;
import com.tjvib.util.LogUtil;
import com.tjvib.util.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class LocalSensorActivity extends SensorActivity<LocalSensorPresenter, LocalSensorData>
        implements EasyPermissions.PermissionCallbacks {

    public static long firstTimestamp = 0;

    private String[] perms = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private int RC_FINE_STORAGE = 3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "请授予APP存储权限，以实现存储数据功能。", RC_FINE_STORAGE, perms);
            Alerter.create(this).setTitle("存储权限说明").setText("用于存储传感器数据").show();
        }

        sen_tv_tit.setText("手机自带传感器");
        sen_iv_set.setOnClickListener(v ->
                showSettingDialog(SENSOR_TYPE_LOCAL, (dialogInterface, i) -> {
                    switch (i) {
                        case 0:
                            presenter.resetTimestamp();
                            break;
                        case 1:
                            showSetFreqDialog();
                            break;
                    }
        }));
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.startOrBindToService();
    }

    @Override
    protected void onStop() {
        presenter.stopReadingData();
        presenter.stopService();
        super.onStop();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    String getSensorName() {
        return "手机自带传感器";
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_local_sensor;
    }

    @Override
    protected boolean initView() {
        return true;
    }

    @Override
    protected boolean initData() {
        firstTimestamp = 0;
        return true;
    }

    @Override
    void setInfoLayoutData(LocalSensorData data) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        sen_tv_data.setText(getString(
                R.string.ui_local_sensor_data,
                format.format(new Date(data.localtime)),
                data.timestamp,
                data.quat[0], data.quat[1], data.quat[2], data.quat[3],
                data.acc[0], data.acc[1], data.acc[2],
                data.gyr[0], data.gyr[1], data.gyr[2],
                data.mag[0], data.mag[1], data.mag[2],
                data.linAcc[0], data.linAcc[1], data.linAcc[2]));
        sen_tv_info1.setText(getString(R.string.ui_local_sensor_info,
                presenter.getStreamFreq()));
    }

    @Override
    void setImageLayoutData(LocalSensorData data) {
        if (isDrawing) {
            graph2LastXValue = graph2LastXValue + 1.0D;
            float[] dataToShow = new float[3];
            int i = 0;
            if (this.dataSelect == R.id.sen_rb_acc) {
                while (i < 3) {
                    dataToShow[i] = data.acc[i];
                    i += 1;
                }
            } else if (this.dataSelect == R.id.sen_rb_mag) {
                i = 0;
                while (i < 3) {
                    dataToShow[i] = data.mag[i];
                    i += 1;
                }
            } else if (this.dataSelect == R.id.sen_rb_gyr) {
                i = 0;
                while (i < 3) {
                    dataToShow[i] = data.gyr[i];
                    i += 1;
                }
            } else if (this.dataSelect == R.id.sen_rb_lin) {
                i = 0;
                while (i < 3) {
                    dataToShow[i] = data.linAcc[i];
                    i += 1;
                }
            }

            mSeries1.appendData(new DataPoint((data.localtime - firstTimestamp)/1000f, dataToShow[0]), true, 50);
            mSeries2.appendData(new DataPoint((data.localtime - firstTimestamp)/1000f, dataToShow[1]), true, 50);
            mSeries3.appendData(new DataPoint((data.localtime - firstTimestamp)/1000f, dataToShow[2]), true, 50);
        }
    }

    @Override
    protected LocalSensorPresenter genPresenter() {
        return new LocalSensorPresenter(this);
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == R.id.sen_rb_acc || buttonView.getId() == R.id.sen_rb_mag
                || buttonView.getId() == R.id.sen_rb_gyr || buttonView.getId() == R.id.sen_rb_lin) {
            if (isChecked) {
                dataSelect = buttonView.getId();
                removeGraph();
                drawGraph();
            }
        } else if (buttonView.getId() == R.id.sen_cb_x) {
            LogUtil.e(mSeries1.toString());
            if (isChecked) sen_gv_data.addSeries(mSeries1);
            else sen_gv_data.removeSeries(mSeries1);
        } else if (buttonView.getId() == R.id.sen_cb_y) {
            if (isChecked) sen_gv_data.addSeries(mSeries2);
            else sen_gv_data.removeSeries(mSeries2);
        } else if (buttonView.getId() == R.id.sen_cb_z) {
            if (isChecked) sen_gv_data.addSeries(mSeries3);
            else sen_gv_data.removeSeries(mSeries3);
        }
//            case R.id.radioStop:
//                if (isChecked) {
//                    removeGraph();
//                    dataSelect = 0;
//                }
//                break;
    }


    public void showSetFreqDialog() {
        String[] freqSelection = new String[]{"5", "10", "25", "50", "100", "200", "400"};
        new AlertDialog.Builder(this)
                .setTitle("设置频率(Hz)")
                .setItems(freqSelection, (dialog, which) -> presenter.setStreamFreq(Integer.parseInt(freqSelection[which])))
                .create()
                .show();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            ToastUtil.show("请您前往本手机设置手动开启权限");
        }
    }
}